package ginMiddleware

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func CorsAll() gin.HandlerFunc {
	config := cors.DefaultConfig()
	config.AllowCredentials = true
	config.AllowFiles = true
	config.AllowWebSockets = true
	config.AllowAllOrigins = true
	config.AllowMethods = []string{"OPTIONS"}
	config.AddAllowHeaders("Access-Control-Allow-Origin", "Origin")
	return cors.New(config)

}

// Cors 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token,Authorization")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		c.Header("Access-Control-Expose-Headers", "Access-Control-Allow-Origin,Content-Type,Authorization")
		c.Header("Access-Control-Allow-Credentials", "true")
		//放行所有OPTIONS方法
		if strings.ToUpper(c.Request.Method) == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}
		// 处理请求
		c.Next()
	}
}
